//
//  UIViewController+Extension.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/12.
//

import Foundation
import UIKit

var topVc: UIViewController? {
    var resultVc: UIViewController?
    resultVc = _topVc(UIApplication.shared.keyWindow?.rootViewController)
    while resultVc?.presentedViewController != nil {
        resultVc = _topVc(resultVc?.presentedViewController)
    }
    return resultVc
}


private func _topVc(_ vc: UIViewController?) -> UIViewController? {
    if vc is UINavigationController {
        return _topVc((vc as? UINavigationController)?.topViewController)
    } else if vc is UITabBarController {
        return _topVc((vc as? UITabBarController)?.selectedViewController)
    } else {
        return vc
    }
}

extension UIViewController {
    /// 当push时移除当前控制器
    func removeCurrentVcWhenPush(_ vc: UIViewController, animated: Bool = true) {
        if let nav = navigationController {
            nav.pushViewController(vc, animated: animated)
            if var vcs = vc.navigationController?.viewControllers {
                // 移除当前控制器
                if let index = vcs.firstIndex(of: self), vcs.count > index {
                    vcs.remove(at: index)
                }
                vc.navigationController?.viewControllers = vcs
            }
        }
    }
    
    /// 获取当前控制器
    static var current: UIViewController? {
        var window = UIApplication.shared.keyWindow
        // 是否为当前显示的window
        if window?.windowLevel != .normal {
            let windows = UIApplication.shared.windows
            for windowTemp in windows {
                if windowTemp.windowLevel == .normal {
                    window = windowTemp
                    break
                }
            }
        }
        
        let vc = window?.rootViewController
        return findVc(vc)
    }
    
    private static func findVc(_ currentVc: UIViewController?) -> UIViewController? {
        guard let vc = currentVc else { return nil }
        
        if let presented = vc.presentedViewController {
            return findVc(presented)
        } else if let nav = vc as? UINavigationController {
            return findVc(nav.visibleViewController)
        } else if let tabVc = vc as? UITabBarController {
            return findVc(tabVc.selectedViewController)
        } else {
            return vc
        }
    }
}
